/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ch.lab24.android.rtm;

import android.app.Service;
import android.app.PendingIntent;
import android.app.AlarmManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.content.Intent;
import android.content.Context;
import android.database.ContentObserver;

import java.util.Calendar;
import java.util.GregorianCalendar;

import ch.lab24.rtm.ServiceException;

/**
 * CheckUpdateService checks every 24 hours if updates have been made to the photostreams
 * of the current contacts. This service simply polls an RSS feed and compares the
 * modification timestamp with the one stored in the database.
 */
public class SyncService extends Service {
    private static boolean DEBUG = false;

    // Check interval: every 15 Minutes
    private static long UPDATES_CHECK_INTERVAL = 5 * 60 * 1000;

    private CheckForUpdatesTask mTask;

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        (mTask = new CheckForUpdatesTask()).execute();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mTask != null && mTask.getStatus() == UserTask.Status.RUNNING) {
            mTask.cancel(true);
        }
    }

    public IBinder onBind(Intent intent) {
        return null;
    }

    static void schedule(Context context) {
        final Intent intent = new Intent(context, SyncService.class);
        final PendingIntent pending = PendingIntent.getService(context, 0, intent, 0);

        Calendar c = new GregorianCalendar();
        c.add(Calendar.DAY_OF_YEAR, 1);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);

        final AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarm.cancel(pending);
        if (DEBUG) {
            alarm.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),
                    2 * 60 * 1000, pending);
        } else {
            alarm.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + (30 * 1000),
            		UPDATES_CHECK_INTERVAL, pending);
//            alarm.setRepeating(AlarmManager.RTC, c.getTimeInMillis(),
//                    UPDATES_CHECK_INTERVAL, pending);
        }
    }

    private class CheckForUpdatesTask extends UserTask<Void, Object, Void> {
        
        @Override
        public void onPreExecute() {        	
        }

        private ContentObserver mObserver = new ContentObserver(new Handler()) {
            @Override
            public boolean deliverSelfNotifications() {
                return true;
            }
        };
        
        public Void doInBackground(Void... params) {
	        try
			{
	        	(new RTMInvoker(SyncService.this)).update();
	        	getContentResolver().notifyChange(RememberTheMilk.SYNCSERVICE_URI, mObserver);
	        	
			}
			catch (ServiceException se)
			{
			}    			    	
            return null;
        }

        @Override
        public void onProgressUpdate(Object... values) {
        }

        @Override
        public void onPostExecute(Void aVoid) {
            stopSelf();
        }
    }
}
